The overloading mechanism should be used in place of optional parameters for several reasons:
- Optional parameter values are baked into the method call site code, thus, if a default value has been changed, all referencing assemblies need
to be rebuilt, otherwise the original values will be used.
- The Common Language Specification (CLS) allows compilers to ignore default parameter values, and thus require the caller to explicitly specify
the values. For example, if you want to consume a method with default argument from another .NET compatible language (for instance C++/CLI), you
will have to provide all arguments. When using method overloads, you could achieve similar behavior as default arguments.
- Optional parameters prevent muddying the definition of the function contract. Here is a simple example: if there are two optional parameters,
when one is defined, is the second one still optional or mandatory?
Noncompliant code example
Sub Notify(ByVal Company As String, Optional ByVal Office As String = "QJZ") ' Noncompliant
End Sub
Compliant solution
Sub Notify(ByVal Company As String)
Notify(Company, "QJZ")
End Sub
Sub Notify(ByVal Company As String, ByVal Office As String)
End Sub
Exceptions
The rule ignores non externally visible methods.